<?php

class model_resource extends model_version{
	public $pk = "uuid";
	public $table = "resource";
	
	public function createByTmpFile($tmpFilePath,$deleteTmpFile = true){
		if ( !file_exists($tmpFilePath) ) {
			throw new Exception($tmpFilePath.' doest not exist on disk');
		}
		$ext = Util::getFileExt($tmpFilePath);
		$target_file_name = time().'.'.Util::makeRandomStr(4).'.'.$ext;
		$target_path = ASSETS_DIR.'/'.$target_file_name;
		copy($tmpFilePath,$target_path);
		$row['path'] = $target_file_name;
		
		if ( $deleteTmpFile ) {
			unlink($tmpFilePath);
		}
		return  parent::create($row);
	}
	public function updateByTmpFile($tmpFilePath,$uuid,$deleteTmpFile = true){
		$exist_source_data = $this->get($uuid);
		
		if ( !file_exists($tmpFilePath) ) {
			throw new Exception($tmpFilePath.' doest not exist on disk');
		}
		if ( strlen($exist_source_data['path']) > 0) {
			unlink(APP_PATH.'/upload/assets/'.$exist_source_data['path']);
		}
		
		$ext = Util::getFileExt($tmpFilePath);
		$target_file_name = time().'.'.Util::makeRandomStr(4).'.'.$ext;
		$target_path = ASSETS_DIR.'/'.$target_file_name;
		copy($tmpFilePath,$target_path);
		$exist_source_data['path'] = $target_file_name;
		
		
		if ( $deleteTmpFile ) {
			unlink($tmpFilePath);
		}
		return  parent::update(array($this->pk=>$exist_source_data[$this->pk]),$exist_source_data);
	}
	public function deleteByPk($pk)
	{
		$exist_data = $this->get($pk);
		if ( strlen($exist_data['path']) > 0) {
			unlink(APP_PATH.'/upload/assets/'.$exist_data['path']);
		}
		parent::model_version_delete_byPk($pk,true);
	}

}

?>